module.exports = function (express, enable, downloadResource) {
    const log4js = require('log4js');
    const logger = log4js.getLogger();

    var fs = require('fs');
    var pathlib = require('path');
    var parseurl = require('parseurl')
    var oldStatic = express.static;
    //简单判断是在mac osx或者在windows中
    var isMac = __dirname.indexOf('/') == 0;
    var newStatic = function (root, options) {
        var opts = Object.create(options || null);
        var originalHandler = oldStatic(root, options);
        var wrappedHandler = function (req, res, next) {
            let originalUrl = req.originalUrl;
            if (originalUrl.indexOf("/api/") == 0) {
                originalHandler(req, res, next);
                return;
            }
            let filepath;
            let driverReg = !isMac ? /^\/(?:file|view)\/([a-zA-Z]+)(\:||%3A)?\// : /^\/(?:file|view)\//;
            let queryMarkIdx = originalUrl.indexOf("?");
            let req_path;
            if (queryMarkIdx != -1) {
                req_path = originalUrl.substr(0, queryMarkIdx);
            } else {
                req_path = originalUrl;
            }
            req_path = decodeURIComponent(req_path);
            let driverResult = req_path.match(driverReg);
            if (driverResult) {
                var driverName = driverResult[1];
                if (!isMac) {
                    filepath = driverName + ":\\" + req_path.substr(driverResult[0].length)
                } else {
                    filepath = "/" + req_path.substr(driverResult[0].length);
                }
            } else {
                let pathname = decodeURIComponent(parseurl(req).pathname);
                filepath = pathlib.join(root, pathname);
            }
            if (enable) {
                var dirpath = pathlib.dirname(filepath);
                var filename = pathlib.basename(filepath);
                // @todo Reading the entire directory listing and then searching it is quite inefficient for large folders 
                // We should find a more efficient way to do this for one file at a time 
                // "https://wegame.girlnames.fun/"
                const willAutoDownload = downloadResource;
                if (willAutoDownload) {
                    // 如果 dirpath 不存在，则创建
                    if (!fs.existsSync(dirpath)) {
                        fs.mkdirSync(dirpath, {recursive: true});
                    }
                }
                fs.readdir(dirpath, function (err, files) {
                    if (err) {
                        handleFavicon(err, req, res, next);
                    } else {
                        var fileIsThere = files.indexOf(filename) >= 0;
                        if (fileIsThere) {
                            originalHandler(req, res, next);
                        } else {
                            // 尝试下载
                            if (willAutoDownload) {
                                let originParts = originalUrl.split("/");
                                originParts = originParts.slice(0, originParts.length - 1);
                                const host = originParts.reverse().find((part, index, arr) => {
                                    return part.indexOf(".") != -1 && !part.match(/^[\d\.]+$/) && part.indexOf("@") == -1;
                                });
                                const urlKey = `/${host}/`;
                                const idx = originalUrl.lastIndexOf(urlKey);
                                if (idx >= 0) {
                                    const target = "https://" + host + "/" + originalUrl.substring(idx + urlKey.length);
                                    // 下载 target 到 filepath
                                    downloadTarget(target);
                                } else {
                                    handleFavicon(`NOT FOUND "${filepath}"`, req, res, next);
                                }
                            } else {
                                handleFavicon(`NOT FOUND "${filepath}"`, req, res, next);
                            }
                        }
                    }

                    function downloadTarget(target) {
                        const request = require("request");
                        const request_progress = require("request-progress");
                        const chunks = [];
                        logger.debug(`[GET] ${target}`);
                        const requestInst = request(target, {
                                proxy: process.env.NODE_AUTOMATOR_PROXY,
                                method: "GET",
                                gzip: true,
                                headers: {
                                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                                    "Referer": target,
                                },
                                rejectUnauthorized: false,
                                timeout: 10 * 60 * 1000, // 超时(ms)
                            }, function (err, ret) {
                                // 把 chunks 写入 filepath
                                if (!err && ret.statusCode > 0 && ret.statusCode < 400) {
                                    let buffer = Buffer.concat(chunks);
                                    let bufferString = buffer.toString();
                                    // TODO: 应该有更好的方式处理
                                    // 匹配到 `No Content:` 需要重新请求真实地址
                                    let noContentMatched = bufferString.match(/^No Content\: (https:\/\/.*)$/);
                                    if (noContentMatched) {
                                        downloadTarget(noContentMatched[1]);
                                    } else {
                                        fs.writeFileSync(filepath, buffer);
                                        res.end(buffer);
                                        process.stdout.write(`\r\x1B[0K`);
                                    }
                                } else {
                                    logger.warn(`[GET] ${target} #${ret?.statusCode} ${err}`);
                                    handleFavicon(err, req, res, next);
                                }
                            })
                            .on("data", (chunk) => {
                                chunks.push(chunk);
                            });
                        request_progress(
                            requestInst.on('progress', function (state) {
                                process.stdout.write(`\rDownloading ${target} [${(state.size.transferred / state.size.total * 100).toFixed(0)}%] ${formatByteSize(state.size.transferred)} / ${formatByteSize(state.size.total)}\x1B[0K`);
                            }
                            )
                        );
                    }
                });
            } else {
                fs.stat(filepath, function (err, stat) {
                    if (err) {
                        handleFavicon(err, req, res, next);
                    } else {
                        originalHandler(req, res, next);
                    }
                });
            }
        };
        return wrappedHandler;
    };

    function handleFavicon(err, req, res, next) {
        if (err) {
            if (req.url.match(/^\/favicon\.(?:ico|png)/)) {
                // var data = 'iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAENFJREFUeJzt3WnMtVdVx+Hf+7aUMpZ5pjZAi6AiQRBUAopBBUWcACMIEoaIYTAIxCEkxuBA4gABBwwKCKiIqAERIYpBHKoEghoUpMwUlUGoDIUO4IddDCDQl/bZ536es68redNv+15nPUn/65x13+cUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8FmObV3AEXZSdXp1ZnWz6gbV9avTqlM2rAtgH11QnVe9rzq3ekf15urt1cXblXV0GQBO3M2qb6puX92uuk116qYVAfCJ6g3Va6uzq1dX51Sf2rKoo8AA8IVdqbpHdc/qm6szNq0GgBN1bvXy6k8v+e/Hti3ncDIAfLYrVN9S3a/6rupq25YDwOV0fvXi6rmNYeCibcs5PAwAwzWqh1WPrm6ycS0AzHFu9YzqNxr3Eixt9QHgxtUTqodUV9m4FgB24/zqt6onV+/euJbNrDoAXKV6fCP8r7RxLQBs4+PV06qfqz60cS07t9oAcLy6f/XzjXf/APDexpvC57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QEEmXh5HL2eAILUM6bDxAQQZOLlcfR6AghSz5gOExNAkImXx9HrCSBIPWM6TEwAQSZeHkevJ4Ag9YzpMDEBBJl4eRy9ngCC1DOmw8QEEGTi5XH0egIIUs+YDhMTQJCJl8fR6wkgSD1jOkxMAEEmXh5HryeAIPWM6TAxAQSZeHkcvZ4AgtQzpsPEBBBk4uVx9HoCfwM2tsTY2IOEsgAAAABJRU5ErkJggg==';
                var img = Buffer.from(data, 'base64');
                res.writeHead(200, {
                        'Content-Type': 'image/png',
                        'Content-Length': img.length
                });
                res.end(img);
                return;
            }
        }
        next(err);
    }
    express.static = newStatic;
};
const KB = 1024;
const MB = 1024 * 1024;
const GB = 1024 * 1024 * 1024;

/**
 * 
 * @param {number} bytes 
 */
function formatByteSize(bytes) {
    if (bytes >= GB) {
        return `${(bytes / GB).toFixed(2)} GB`;
    }
    if (bytes >= MB) {
        return `${(bytes / MB).toFixed(2)} MB`;
    }
    return (bytes / KB).toFixed(2) + " KB";
}